
function extractData(fields) {

    var data = {};
    fields.forEach(function(field) {
      if (field.name == "file") {
        data.filename = field.filename;
        data.content = field.content;
      } else {
        data[field.name] = field.value;
      }
    });
    return data;
}

function isValid(data) {
    return (data.filename !== undefined && data.content !== undefined);
}

function addExpirationDate(uploadedFile, validTo) {
    var aspectProperties = {'cm:to': validTo};
    var aspectAdded = uploadedFile.addAspect("cm:effectivity", 
                                             aspectProperties);
    if (!aspectAdded) {
        logger.error("Effectivity Aspect could not be added"); 
    } else {
        logger.debug("Effectivity Aspect added successfully");
    }
    return aspectAdded;
}

function addVersioningAspect(uploadedFile) {

    // ensureVersioningEnabled(true, true);
    uploadedFile.addAspect("cm:versionable");
 
}

function addTags(documentNode, tagNames) {

    var store = "workspace://SpacesStore";

    function getOrCreateTag(tagName) {
        var tag = taggingService.getTag(store, tagName);
        if (tag === null) {
            return taggingService.createTag(store, tagName);
        } else {
            return tag;
        }
    }

    documentNode.clearTags();

    tagNames.forEach(function(tagName) {
        var tag = getOrCreateTag(tagName);
        documentNode.addTag(tagName);          
    });

}

function getOrCreateFile(folder, filename) {

    var file = folder.childByNamePath(filename);
    if (file === null) {
        var newFile = folder.createFile(filename);
        return {file: newFile, 
                isNew: true};    
    } else {
        return {file: file,
                isNew: false};
    }

}

function uploadFile(data) {

    logger.debug("Uploading file in " + data.folderPath);

    var folder = roothome.childByNamePath(data.folderPath);
    if (folder == null) {
        status.code = 400;
        return {success: false,
                message: "Folder not found: " + data.folderPath};
    }

    var result = getOrCreateFile(folder, data.documentName);
    var uploadedFile = result.file;
    uploadedFile.properties.content.write(data.content);
    uploadedFile.properties.content.setEncoding("UTF-8");
    uploadedFile.properties.content.guessMimetype(data.filename);  
    uploadedFile.properties.title = data.title;
    uploadedFile.properties.description = data.description;
   
    var tags = data.tags.split(",").map(function(tag) { return tag.trim(); });
    var nonEmptyTags = tags.filter(function(tag) { return tag.length > 0; });    
    if (nonEmptyTags.length > 0) {    
        addTags(uploadedFile, nonEmptyTags);
    }

    addExpirationDate(uploadedFile, data.validTo);
    addVersioningAspect(uploadedFile);
    if (!result.isNew) {
        uploadedFile.createVersion("New version", true);
    }
    uploadedFile.save();
    var version = uploadedFile.versionHistory[0];

    return {
        success: true,
        message: "File created successfully",
        data: {version: {label: version.label}}
    };
}

var data = extractData(formdata.fields);
if (!isValid(data)) {
    status.code = 400;
    model.message = jsonUtils.toJSONString({
        success: false,
        message: "Uploaded file cannot be located in request"
    });
} else {
    var result = uploadFile(data);
    model.message = jsonUtils.toJSONString(result);
}